package chapter4.eg10;

import java.util.List;
import java.util.Map;
import java.util.Random;
import org.apache.kafka.clients.producer.Partitioner;
import org.apache.kafka.common.Cluster;
import org.apache.kafka.common.PartitionInfo;

public class AuditPartitioner implements Partitioner {
  private Random random;

  @Override
  public int partition(String topic, Object key, byte[] keyBytes, Object value, byte[] valueBytes,
    Cluster cluster) {
    String k = (String) key;
    List<PartitionInfo> partitionInfos = cluster.availablePartitionsForTopic(topic);
    int count = partitionInfos.size() - 1;
    return k != null && k.contains("audit") ? count : random.nextInt(count);
  }

  @Override
  public void close() {

  }

  @Override
  public void configure(Map<String, ?> configs) {
    random = new Random();
  }
}
